/**
 * 定义公共站点地图模块
 */
(function(window, angular, undefined){
	var StationMapModule = angular.module('water.apps.common.stationMap.stationMapManager', ['waterCommon',
	                                                                                           'water.entity.district',
	                                                                                           'water.common.publishSubscribe',
	                                                                                           'water.entity.monitorStation']);
	StationMapModule.controller('commonStationMapManagerController',function($gisObject,$rootScope,$scope,OperationStationJobService,$districtService,$monitorStationService,$pubSubService){
		//地图复位
		if( $gisObject.map){
			$gisObject.map.setExtent($gisObject.fullExtent);
		}
		
		/**
		 * 站点名称查询信息
		 */
		$scope.stationName;
		/**
		 * 政区数据
		 */
		$scope.area;
		/**
		 * 选择的政区
		 */
		$scope.selectArea;
		/**
		 * 站点列表数据
		 */
		$scope.stationList;
		/**
		 * 标识地图鼠标事件是否注册
		 */
		$scope.graphicLayerEventRegist = false;
		/**
		 * 选择的站点
		 */
		$scope.selectStation;
		/**
		 * 地图上站点图标的目录
		 */
		$scope.stationStatusImgDir = getJsBasePath()+"wdp/images/stationStatus/";
		/**
		 * 政区选择事件
		 */
		$scope.onAreaChange = function(area){
			$scope.selectArea = area.CODE;
			$scope.queryStation();
		}
		/**
		 * 选择转移类型
		 */
		$scope.selectTrasfer='all';
		/**
		 * 转移类型选择事件
		 */
		$scope.onTrasferChange = function(data){
			$scope.selectTrasfer = data.k;
			$scope.queryStation();
		}
		/**
		 * 查询站点
		 */
		$scope.queryStation=function(){
			var queryObj = $scope._getQueryObject();
			$monitorStationService.getListWithCompany(queryObj).then(function(data){
				$scope.stationList = data.data;
				$scope._renderToMap(data.data);
				$scope._registerGraphicMouseEvent();
			});
		};
		/**
		 * 站点状态
		 */
		$scope.getStatusStatistics=function(){
			var queryObj = $scope._getQueryObject();
			$monitorStationService.getStatusStatistics(queryObj).then(function(data){
				$scope.StatusData = data;
			});
		}
		/**
    	 * 公司单击事件
    	 */
    	$scope.companyClick = function(companyGUID){
    		var stataionDivs = $("div[company_guid='"+companyGUID+"']");
    		stataionDivs.animate({height: 'toggle', opacity: 'toggle'}, "fast");
    	}
		
		/**
		 * Graphi的鼠标悬浮或者离开事件
		 */
		$scope.onGraphicMouseOverOrLeave = function (evt){
	    	var graphic = evt.graphic;
	    	
    		if(evt.type==="mouseover"){
	    		$gisObject.map.setMapCursor("pointer");
	    		graphic.setSymbol(graphic.heightLightSymbol);
	    	}
	    	else{
	    		$gisObject.map.setMapCursor("default");
	    		graphic.setSymbol(graphic.defaultSymbol);
	    	}
	    }
		/**
		 * 地图Graphic鼠标点击事件
		 */
		$scope.onGraphicClick = function(evt){
			var graphic = evt.graphic;
			$scope.showAllStationData = false;
			$gisObject.map.infoWindow.setTitle(getInfoTemplateTitle(graphic));
			setContentAndShow(graphic);
		}
		
		/**
		 * 站点列表项点击事件
		 */
		$scope.onStationClick = function(station){
			$gisObject.map.infoWindow.hide();
			$scope.selectStation = station;
			var graphic =  $scope._createFeatureFromStation(station);
			$scope.onGraphicClick({graphic:graphic});
			$gisObject.map.centerAndZoom(graphic.geometry,3);
		}
		
		/**
		 * 站点定位点击事件
		 */
		$scope.onLocateClick = function(station){
			$gisObject.map.infoWindow.hide();
			var graphic = $scope._createFeatureFromStation(station);
			$scope.onGraphicClick({graphic:graphic});
			$gisObject.map.centerAndZoom(graphic.geometry,3);
		}
		
		/**
		 * 把站点数据转换成feature添加到地图上
		 */
		$scope._renderToMap = function(data){
			$gisObject.map.graphics.clear();
			$gisObject.map.infoWindow.hide();
			for(var i=0;i<data.length;i++){
				var item = data[i];
				var graphic = $scope._createFeatureFromStation(item);
				$gisObject.map.graphics.add(graphic);
			}
		}
		
		/**
		 * 通过station数据构造feature
		 */
		$scope._createFeatureFromStation = function(station){
			var point = new esri.geometry.Point({
				 x:station.X,
				 y:station.Y,
				 spatialReference:$gisObject.map.spatialReference
				});  
			var defaultSymbol = $scope._getDefaultSymbol(station);
			var heightLightSymbol = $scope._getHighlightSymbol();
			var graphic =  new esri.Graphic(point,defaultSymbol,{});
			graphic.attributes = station;
			graphic.defaultSymbol = defaultSymbol;
			graphic.heightLightSymbol = heightLightSymbol;
			return graphic;
		}
		
		/**
		 * 获取查询参数
		 */
		$scope._getQueryObject = function(){
			var waterType = getWaterType();
			var queryObj = {
					DISTRICT:$scope.selectArea,
					WATER_TYPE:waterType,
					BUILD_STATUS:'0',
					STATION_NAME:$scope.stationName,
					TRASFER_TYPE:$scope.selectTrasfer
			};
			if($scope.selectArea == 'all'){
				delete queryObj.DISTRICT;
			}
			return queryObj;
		}
		/**
		 * 根据站点的状态获取地图样式
		 */
		$scope._getDefaultSymbol = function(data){
			var imgUrl = "online.png";
			if(data.STATION_STATUS == null ||data.STATION_STATUS == ""){
				imgUrl = "3.png";
			}
			else{
				imgUrl = data.STATION_STATUS+".png";
			}
			var symbol = new esri.symbol.PictureMarkerSymbol($scope.stationStatusImgDir+imgUrl,16,16);
			return symbol;
		}
		/**
		 * 高亮符号
		 */
		$scope._getHighlightSymbol = function(){
			var iconURL = getJsBasePath()+"/wdp/images/highlight.png";
			var pMark = new esri.symbol.PictureMarkerSymbol(iconURL, 20, 20);
			return pMark;
		}
		
		/**
		 * 加载政区数据
		 */
		function _initArea(){
			$districtService.getDistrictDomain().then(function(data){
				$scope.area = data.qu;
			});
			$pubSubService.subscribe("mapAreaChange",function(event,data){
				$scope.onAreaChange(data);
			},$scope);
		}
		
		/**
		 * 注册graphic的鼠标事件
		 */
		$scope._registerGraphicMouseEvent = function(){
			if(!$scope.graphicLayerEventRegist){
				dojo.connect($gisObject.map.graphics, "onMouseOver", $scope.onGraphicMouseOverOrLeave);
				dojo.connect($gisObject.map.graphics, "onMouseOut", $scope.onGraphicMouseOverOrLeave);
				dojo.connect($gisObject.map.graphics, "onClick", $scope.onGraphicClick);
				$scope.graphicLayerEventRegist = true;
			}
		}
		
		function getInfoTemplateTitle(feature){
			var o = feature.attributes;
			var name = o.NAME;
			if(o.$searchName=='wsc'){
				name=o['SDE.PS_WWTPM.NAME'];
			}
			var title = '<b>' + name + '</b>';
			if(o.$searchName=='station'){
				title += '&nbsp;&nbsp<a id="btnDetail" style="cursor:pointer;color:#3d6dcc;text-decoration:none">详情»</a>';
				$('.esriPopup').undelegate('#btnDetail',"click").delegate('#btnDetail',"click",function(event){
					$scope.openStationDetailWindow(feature);
					$scope.safeApply();
				});
			}
			return title;
		}
		
		function setContentAndShow(feature){
			var o = feature.attributes;
			var image= getJsBasePath()+ 'wdp/images/noPic.png';
			var video="";
			
			OperationStationJobService.postQuery("/RemoteControl/getStationInfo.do",{mn:o.DEVICE_NUM}).then(function(data){
				if(o.PHOTO){
					image = getHostBase() + firstImgUrl(o.PHOTO);
				}
				//重置样式
				$(".gis_win_left").css("display","none");
				$(".esriPopup .sizer").css("width","375px");
				$(".esriPopup .contentPane").css("max-height","330px");
				
				$('.esriPopup').undelegate('li',"click").delegate('li',"click",function(event){
					$('.esriPopup #radius').val(parseInt($(this)[0].innerText));
				});
				var alldata=data;
				$gisObject.map.infoWindow.setContent(getGISWindowsHTML(image,alldata.parmData));
				$gisObject.map.infoWindow.resize(375,410);
				$gisObject.map.infoWindow.show(feature.geometry);
				$gisObject.map.centerAndZoom(feature.geometry,3);
			});
		}
		
		function getGISWindowsHTML(image,pollData){
			var parm = '';
			if(pollData){
				angular.forEach(pollData,function(value,key){
					if(!value.MEAS){
						return;
					}
					parm += "<tr> ";
					parm += ' <td> ' + value.POLLNAME+'：</td><td style="word-wrap:break-word;width:120px;">'+value.MEAS+" "+ value.UNIT + "</td>";
					parm += "</tr> ";
				});
			}
			
			var html = '<div class="gis_win_main" style="font-size: 12px;font-family: \'Microsoft YaHei\', verdana, tahoma;">'+
						   '<div class="gis_win_left" style="float:left;width:355px">'+
								  '<div style="float:left;">'+
									'<div style="float:left;">'+
										'<img onclick="imgShow($(this))" style="cursor:pointer;width:130px;height:195px;" src="'+image+'" />'+
									'</div>'+
									'<div style="float:left;">'+
										' <div style="overflow:auto;height:210px;">'+
											'  <table style="min-width:190px" class="zs-form-tab" id="stationPollData">	'+
											'<tbody>'+parm+'</tbody>'+
											 ' </table>'+
										 '</div>'+
									'</div>	'+
							  ' </div>'+
						  ' <div class="gis_win_right" style="width:384px;height:300px;float:left;display:none">'+
								'<div id="windivPlugin" ></div>'+
						  ' </div>	 '+
					 ' </div>';
			return html;
		}
		
		function firstImgUrl(url){
			if(url.indexOf("|") > 0)
			{
				 var arr = url.split("|");
				 return String(arr[arr.length-1].toString().split(":")[0]);
		    }
			 else{
				 var arr = url.split(":");
				return String(arr[0]);
			 }
		}
		
		if($gisObject.mapInit && $gisObject.map.graphics != null){
			$scope.queryStation();
        }else{
        	var mapInitWatch = $scope.$watch(function(){return $gisObject.mapInit;},function(){
	            if($gisObject.mapInit){
	            	$scope.queryStation();
	            	mapInitWatch();
	            }
	        });
        }
		_initArea();
		$scope.getStatusStatistics();
	});
}(window, angular));


